from fastapi import FastAPI, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import uvicorn
from dotenv import load_dotenv
import os

from routers import dashboard, chat, data_sources, ai_decision
from database import engine, Base
from services.cache_service import redis_client

# 加载环境变量
load_dotenv()

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行
    print("🚀 启动辅助决策系统...")
    
    # 创建数据库表
    Base.metadata.create_all(bind=engine)
    
    # 测试Redis连接
    try:
        await redis_client.ping()
        print("✅ Redis连接成功")
    except Exception as e:
        print(f"❌ Redis连接失败: {e}")
    
    yield
    
    # 关闭时执行
    print("🛑 关闭辅助决策系统...")

# 创建FastAPI应用
app = FastAPI(
    title="辅助决策系统 API",
    description="基于AI的智能辅助决策系统后端API",
    version="1.0.0",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(dashboard.router, prefix="/api/dashboard", tags=["仪表盘"])
app.include_router(chat.router, prefix="/api/chat", tags=["AI对话"])
app.include_router(data_sources.router, prefix="/api/data-sources", tags=["数据源"])
app.include_router(ai_decision.router, prefix="/api/ai-decision", tags=["AI决策"])

@app.get("/")
async def root():
    return {
        "message": "欢迎使用辅助决策系统 API",
        "version": "1.0.0",
        "docs": "/docs",
        "status": "running"
    }

@app.get("/health")
async def health_check():
    return {"status": "healthy", "timestamp": "2024-01-01T00:00:00Z"}

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )
